<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-02-16 18:38:00
 * @Last Modified time: 2023-02-17 16:49:57
 */
namespace app\common\services\store;

use frank\base\BaseService;
use frank\exception\CommonException;
use frank\utils\helper\ArrayHelper;
use app\common\dao\store\GoodsCommentDao;
use app\common\services\store\OrderService;
use app\common\services\store\OrderGoodsService;

/**
 * Class GoodsCommentService
 */
class GoodsCommentService extends BaseService
{

	public $action = 1;

    /**
     * GoodsCommentService constructor.
     * @param GoodsCommentDao $dao
     */
    public function __construct(GoodsCommentDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 获取列表
     */
    public function getGoodsCommentList(array $params)
    {
        [$page, $limit] = $this->getPageValue();
        $where = [];
        if(!empty($params['group_id']) && $params['group_id'] != -1){
            $where['group_id'] = $params['group_id'];
        }
        $list = $this->dao->getGoodsCommentList($where, $page, $limit);
        return $list;
    }

    /**
     * 验证订单是否允许评价
     */
    public function checkOrderAllowComment($orderId)
    {
        $order = OrderService::instance()->getOrderDetail([
            'id'=>$orderId
        ]);
        // 验证订单是否已完成
        if ($order['order_status']['value'] != 1) {
            $this->error = '该订单未完成，无法评价';
            return false;
        }
        // 验证订单是否已评价
        if ($order['comment_status'] == 1) {
            $this->error = '该订单已完成评价';
            return false;
        }
        return true;
    }

    /**
     * 获取待评价商品列表
     */
    public function getNotCommentGoodsList($orderId){
        $goodsList = OrderGoodsService::instance()->getNotCommentGoodsList($orderId);
        return $goodsList;
    }

     /**
     * 根据已完成订单商品 添加评价
     */
    public function createForOrder($uid,$orderId,$formData)
    {
        $goodsList = $this->getNotCommentGoodsList($orderId);
        // 生成评价数据
        $data = $this->createCommentData($uid,$orderId,$goodsList,$formData);
        if (empty($data)) {
            throw new CommonException('没有输入评价内容');
        }
        return $this->transaction(function () use ($orderId, $goodsList, $formData, $data) {
            // 记录评价内容
            $result = $this->saveAll($data);
            // 更新订单评价状态
            $isComment = count($goodsList) === count($data);
            $this->updateOrderIsComment($orderId, $isComment, $result);
            return true;
        });
    }

    /**
     * 生成评价数据
     */
    private function createCommentData($userId, $orderId,$goodsList, $formData)
    {
        $data = [];
        foreach ($goodsList as $goods) {
            if (!isset($formData[$goods['id']])) {
                throw new CommonException('提交的数据不合法');
            }
            $item = $formData[$goods['id']];
            !empty($item['content']) && $data[$goods['id']] = [
                'rate' => $item['rate'],
                'content' => $item['content'],
                'imgs' =>$item['imgs'],
                'sort' => 100,
                'status' => 1,
                'user_id' => $userId,
                'order_id' => $orderId,
                'goods_id' => $item['goods_id'],
                'order_goods_id' => $item['order_goods_id'],
            ];
        }
        return $data;
    }


    /**
     * 更新订单评价状态
     */
    private function updateOrderIsComment($orderId, $isComment, $commentList)
    {
        // 更新订单商品
        $orderGoodsData = [];
        $orderGoodsIds = ArrayHelper::getArrayColumn($commentList,'order_goods_id');
        OrderGoodsService::instance()->update(['id'=>$orderGoodsIds],['comment_status'=>1]);
        // 更新订单
        $isComment && OrderService::instance()->update($orderId,['comment_status' => 1]);
        return true;
    }
}